﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;
using BankCreditPortfolio.DAL.Services;

namespace BankCreditPortfolio.Helpers
{
    public static class ServiceHelper
    {
        public static void ProceedPayments()
        {
            while (true)
            {
                var service = (new AgreementService());
                var agreements = service.GetAll();
                //TODO: service!!!
                foreach (var agreement in agreements)
                {

                    var order = agreement.Order;
                    var AgreementId = agreement.AgreementId;
                    var Currency = order.Currency.Title;
                    var amount = order.Amount*(1 + order.Tariff.CreditPercent/100);
                    var time = order.Tariff.Time;
                    var first = order.Tariff.FirstPayment*amount/100;
                    var other = order.Tariff.OtherPayments*amount/100;
                    var period = (time.Year - 2000)*365 + time.Month*30;
                    var requiredPaymentCount = Math.Round((amount - first)/other + Convert.ToDecimal(0.5)) + 1;
                    var paymentsCount = (new PaymentService()).CreateQuery().Where(
                        x => x.Deposit.DepositId == agreement.Credit.Deposit.DepositId).Count();
                    var nextPayment = agreement.Credit.DeliveryDate.AddDays
                        (Convert.ToDouble(period/requiredPaymentCount)*(paymentsCount + 1));
                    // end
                    agreement.Order.Tariff.Fine = nextPayment < DateTime.Now
                                                      ? (DateTime.Now - nextPayment).Days*agreement.Order.Tariff.Fine
                                                      : 0;
                    var saveAgreement = agreement;
                    try
                    {
                        service.Save(ref saveAgreement);
                    }
                    catch
                    {
                    }

                }
                Thread.Sleep(24*60*60*1000);
            }
        }
    }
}